package com.tim.app.ui.activity.selected;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.ClickUtil;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_App;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.entry.Topic;
import com.tim.app.server.result.PublishProblemResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.TopicListResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.adapter.selceted.GoodAtTopicAdapter;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择话题
 */
public class SelectTopicActivity extends BaseActivity implements BaseRecyclerAdapter.OnItemClickListener, TextWatcher, LoadMoreHandler {

    private static final String TAG = "SelectTopicActivity";

    private ImageButton ibBack;
    private TextView tvSend;
    private TextView tvPromptTitle;
    private HorizontalScrollView hsvSubject;
    private LinearLayoutCompat llSubject;
    private EditText etSearch;

    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvSubject;

    private List<Topic> dataList;
    private GoodAtTopicAdapter adapter;

    private List<Topic> selectTopic;

    private EmptyLayout emptyLayout;

    private String title;
    private String content;
    private String image;
    private boolean isAnonymous;

    private int pageNumber = 1;

    private boolean isEditProblem;//编辑问题
    private Problem problem;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_select_subject;
    }

    /**
     * 编辑问题
     *
     * @param context
     * @param data
     */
    public static void startWithEditProblem(Activity context, Problem data) {
        Intent intent = new Intent(context, SelectTopicActivity.class);
        intent.putExtra(AppKey.PROBLEM, data);
        intent.putExtra("isEditProblem", true);
        context.startActivityForResult(intent, AppKey.REQUEST_CODE_PROBLEM_CONTENT);
    }

    @Override
    public void initView() {
        tvSend = (TextView) findViewById(R.id.tvSend);
        tvPromptTitle = (TextView) findViewById(R.id.tvPromptTitle);
        ibBack = (ImageButton) findViewById(R.id.ibBack);
        ibBack.setOnClickListener(this);
        tvSend.setOnClickListener(this);

        hsvSubject = (HorizontalScrollView) findViewById(R.id.hsvSubject);
        llSubject = (LinearLayoutCompat) findViewById(R.id.llSubject);
        etSearch = (EditText) findViewById(R.id.etSearch);

        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvSubject = (WrapRecyclerView) findViewById(R.id.wrvSubject);
        wrvSubject.setOverScrollMode(View.OVER_SCROLL_NEVER);

        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);
        selectTopic = new ArrayList<>();

        emptyLayout = new EmptyLayout(this, load_more);
        emptyLayout.showContent();
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_search);
        emptyLayout.setEmptyText("没有找到你想要的内容", "");
        tvPromptTitle.setVisibility(View.VISIBLE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvSubject.setLayoutManager(layoutManager);

        dataList = new ArrayList<>();
        adapter = new GoodAtTopicAdapter(this, dataList, false);
        adapter.setOnItemClickListener(this);
        wrvSubject.setAdapter(adapter);
        etSearch.addTextChangedListener(this);

        if (getIntent().hasExtra("isEditProblem")) {
            isEditProblem = getIntent().getBooleanExtra("isEditProblem", false);
            problem = (Problem) getIntent().getSerializableExtra(AppKey.PROBLEM);
            if (null != problem && problem.getTopicList() != null)
                for (int i = 0; i < problem.getTopicList().size(); i++) {
                    addSubject(problem.getTopicList().get(i));
                }
        } else {
            if (getIntent().hasExtra(AppKey.QUESTION_TITLE)) {
                title = getIntent().getStringExtra(AppKey.QUESTION_TITLE);
            }
            if (getIntent().hasExtra(AppKey.QUESTION_CONTENT)) {
                content = getIntent().getStringExtra(AppKey.QUESTION_CONTENT);
            }
            if (getIntent().hasExtra(AppKey.QUESTION_HEAD_IMAGE)) {
                image = getIntent().getStringExtra(AppKey.QUESTION_HEAD_IMAGE);
            }
            if (getIntent().hasExtra(AppKey.IS_ANONYMOUS)) {
                isAnonymous = getIntent().getBooleanExtra(AppKey.IS_ANONYMOUS, false);
            }
        }
    }

    @Override
    public void initData() {
        search(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        OkHttpUtils.getInstance().cancelTag(GoodAtTopicAdapter.TAG);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        search(false);
    }

    /**
     * 搜索
     */
    private void search(boolean isLoadmore) {
        String keyWord = etSearch.getText().toString().trim();
        if (TextUtils.isEmpty(keyWord)) {
            if (!isLoadmore) {
                pageNumber = 1;
                API_Found.ins().getRecommandTopicForAskQuestion(TAG, "", pageNumber, AppKey.PAGE_SIZE, refreshCallback);
            } else {
                API_Found.ins().getRecommandTopicForAskQuestion(TAG, "", pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
            }
        } else {
            if (!isLoadmore) {
                pageNumber = 1;
                API_Found.ins().getRecommandTopicForAskQuestion(TAG, keyWord, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
            } else {
                API_Found.ins().getRecommandTopicForAskQuestion(TAG, keyWord, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
            }
        }
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                TopicListResult result = new Gson().fromJson(resultValue, TopicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            dataList.addAll(result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                        }
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                }
                if (dataList == null || dataList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                TopicListResult result = new Gson().fromJson(resultValue, TopicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            dataList.addAll(result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                        }
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                }

            } else {
            }
            return false;
        }
    };

    @Override
    public void onBackPressed() {
        SoftKeyboardUtil.hideSoftKeyboard(etSearch);
        super.onBackPressed();
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (selectTopic.size() == 5) {
            ToastUtil.showToast("最多添加5个话题");
        } else {
            Topic subject = dataList.get(position);
            for (int i = 0; i < selectTopic.size(); i++) {
                if (subject.getId().equals(selectTopic.get(i).getId())) {
                    subject.setChecked(true);
                    dataList.set(position, subject);
                    return;
                }
            }
            if (!subject.isChecked()) {
                dataList.get(position).setChecked(true);
                addSubject(subject);
            }
        }
    }

    /**
     * 添加话题
     *
     * @param topic
     */

    private void addSubject(final Topic topic) {
        final TextView textView = new TextView(this);
        textView.setText(topic.getTopicName());
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11);
        textView.setBackground(getResources().getDrawable(R.drawable.bg_shape_gray_round));
        textView.setTextColor(getResources().getColor(R.color.text_desc_color));
        textView.setPadding((int) RT.getDensity() * 9, (int) RT.getDensity() * 1, (int) RT.getDensity() * 9, (int) RT.getDensity() * 1);
        textView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                llSubject.removeView(textView);
                selectTopic.remove(topic);
                for (int i = 0; i < dataList.size(); i++) {
                    if (dataList.get(i).getId().equals(topic.getId())) {
                        dataList.get(i).setChecked(false);
                        adapter.notifyDataSetChanged();
                    }
                }
                if (selectTopic.size() == 0) {
                    hsvSubject.setVisibility(View.GONE);
                    tvSend.setEnabled(false);
                    tvPromptTitle.setText("至少添加一个话题");
                }
                if (selectTopic.size() > 0 && selectTopic.size() < 5) {
                    tvPromptTitle.setText("已添加的话题可点选删除");
                    etSearch.setVisibility(View.VISIBLE);
                }
            }
        });
        selectTopic.add(topic);
        llSubject.addView(textView);
        hsvSubject.setVisibility(View.VISIBLE);
        if (selectTopic.size() > 0 && selectTopic.size() < 5) {
            tvPromptTitle.setText("已添加的话题可点选删除");
        }
        if (selectTopic.size() == 0) {
            tvPromptTitle.setText("至少添加一个话题");
        } else {
            tvSend.setEnabled(true);
        }
        if (selectTopic.size() == 5) {
            etSearch.setVisibility(View.GONE);
            tvPromptTitle.setText("已到达话题添加上限");
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvSend:// 发送数据结构
                if (ClickUtil.isFastDoubleClick()) return;
                SoftKeyboardUtil.hideSoftKeyboard(etSearch);
                if (isCanSend) {
                    isCanSend = false;
                    if (isEditProblem) {
                        modtifyProblem();
                    } else {
                        publishProblem();
                    }
                }
                break;
            case R.id.ibBack:
                SoftKeyboardUtil.hideSoftKeyboard(etSearch);
                finish();
                break;
        }
    }

    boolean isCanSend = true;//允许发送

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 发布问题
     */
    private void publishProblem() {
        String topidIds = "";
        for (int i = 0; i < selectTopic.size(); i++) {
            topidIds += selectTopic.get(i).getId() + ",";
        }
        topidIds = topidIds.substring(0, topidIds.length() - 1);
        API_Found.ins().publishProblem(TAG, topidIds, title, content, image, isAnonymous, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                isCanSend = true;
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    API_Statistics.ins().addActionData(TAG, SelectTopicActivity.this, AppKey.TYPE_PROBLEM);
                    PublishProblemResult result = new Gson().fromJson(resultValue, PublishProblemResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getProblem()) {
                        QuestionAndAnswerDetailActivity.start(SelectTopicActivity.this, result.getRes().getProblem(), false);
                        EventManager.ins().sendEvent(EventTag.ON_PROBLEM_ADD, 0, 0, result.getRes().getProblem());
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        ToastUtil.showToast("发送失败");
                    }

                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }


    /**
     * 修改问题
     */
    private void modtifyProblem() {
        String topidIds = "";
        for (int i = 0; i < selectTopic.size(); i++) {
            topidIds += selectTopic.get(i).getId() + ",";
        }
        topidIds = topidIds.substring(0, topidIds.length() - 1);
        API_Found.ins().modtifyProblem(TAG, problem.getId(), topidIds, problem.getTitle(), problem.getContent(), problem.getImage(), problem.getIsAnonymous(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                isCanSend = true;
                if (errCode == ResponseResult.ResultStatus.OK) {
                    EventManager.ins().sendEvent(EventTag.ON_PROBLEM_EDIT, 0, 0, null);
                    setResult(RESULT_OK);
                    finish();
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }


    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        search(true);
    }

}
